<script setup lang="ts">
import { onMounted, reactive } from 'vue';
import { showLoading } from '@tarojs/taro';
import { state } from './state';
import { QUERY_ASSET_LIST } from '/@/api/modules/equipment/asset-manage';
import DeviceAccountSearch from './components/device-account-search.vue';
import DeviceAccountItem from './components/device-account-item.vue';

/**
 * 列表刷新
 */
function refreshList() {
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.list = [];
  onLoading();
}

/**
 * @description 资产列表查询
 * @param {Number} page -当前页
 * @param {Number} pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 10) {
  if (!page && state.finished) return;
  state.loading = true;
  showLoading();
  QUERY_ASSET_LIST({
    comQuery: { page, pageSize },
    keyword: filter.searchValue,
    assetTypeId: filter.searchType,
    assetInfo: { areaId: filter.searchRegion },
  })
    .then((res) => {
      state.loading = false;

      if (
        state.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      )
        state.finished = true;
      if (!res.assetInfoList || !res.assetInfoList.length) return;

      res.assetInfoList.forEach((item) => state.list.push(item));

      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;
  queryList(state.activePage);
}

/**
 * 页面挂载时候，加载请求
 */
onMounted(() => {
  refreshList();
});

/**
 * 搜索相关项
 */
const filter = reactive<{
  /**
   * 资产名称（查询资产）
   */
  searchValue: string;
  /**
   * 区域id（查询区域）
   */
  searchRegion: string;
  /**
   * 资产类型id(查询资产类型)
   */
  searchType: string;
}>({
  searchValue: '',
  searchRegion: '',
  searchType: '',
});

/**
 * 搜索框选择过滤条件
 * @param searchValue
 * @param searchRegion
 * @param searchType
 */
function filterSearch(searchValue: string, searchRegion: string, searchType: string) {
  filter.searchValue = searchValue;
  filter.searchRegion = searchRegion;
  filter.searchType = searchType;
  refreshList();
}
</script>
<template>
  <view class="device-list app-page--1">
    <app-navbar title="资产台账" />
    <device-account-search @change="filterSearch" />
    <scroll-view
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onLoading()"
    >
      <view class="device-list__wrapper">
        <device-account-item :item="item" v-for="item in state.list" :key="item.id" />
      </view>
      <view class="app-page__list-tips">
        <text v-if="!state.list.length">暂无数据！</text>
        <text v-else-if="state.list.length && state.loading">加载中...</text>
        <text v-else-if="state.list.length && state.finished">加载完成!</text>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
